package com.hopu.oa.controller.notemanage;


import com.hopu.oa.controller.process.NewProcessController;
import com.hopu.oa.dao.notemanage.AoaNoteListDao;

import com.hopu.oa.entity.management.AoaStatusList;
import com.hopu.oa.entity.management.AoaTypeList;
import com.hopu.oa.entity.notemanage.AoaCatalog;
import com.hopu.oa.entity.notemanage.AoaNoteList;
import com.hopu.oa.entity.notemanage.AoaReceiverNote;
import com.hopu.oa.entity.process.AoaAttachmentList;
import com.hopu.oa.entity.user.AoaUser;
import com.hopu.oa.service.notemanage.NoteManageService;

import com.hopu.oa.service.notemanage.NoteService;
import com.hopu.oa.service.process.NewProcessService2;
import com.hopu.oa.until.OosUtil;
import com.hopu.oa.until.data.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @ClassName: NoteManageController
 * @Description:
 * @Date: 2021/11/30 9:11
 */
@Controller
public class NoteManageController {
    @Autowired
    private NoteManageService noteManageService;

    @Autowired
    private AoaNoteListDao noteDao;

    @Autowired
    private NoteService noteService;


    @Autowired
    private OosUtil oosUtil;

    @Autowired
    private NewProcessService2 newProcessService2;


    /**
     * 收藏搜索
     *
     * @param isCollected
     * @return
     */
    @RequestMapping("noteTable")
    public String noteTable(Integer isCollected) {
        System.out.println("isCollected = " + isCollected);

        return "forward:notewrite?isCollected=" + isCollected;
    }


    @RequestMapping("noteview")
    public String noteview
            (
                    Model model, HttpSession session,
                    @RequestParam(value = "baseKey", defaultValue = "") String baseKey,
                    @RequestParam(value = "page", defaultValue = "1") int page,
                    @RequestParam(value = "size", defaultValue = "8") int size,
                    @RequestParam(value = "catalogId", defaultValue = "") String catalogId,
                    @RequestParam(value = "typeid", defaultValue = "") String typeid
            ) {

        /*      *//*
            查询全部
        *//*

        System.out.println(catalogId);
        AoaUser user = (AoaUser) session.getAttribute("user");
        //状态，类型
        model.addAttribute("statuslist",
                noteManageService.findStatus());
        model.addAttribute("typelist",
                noteManageService.findType());


        //笔记分类
        model.addAttribute("calist",
                noteManageService.findCatalog(user.getUserId()));
        Integer cid = "".equals(catalogId) ? null : Integer.parseInt(catalogId);
        *//*
          分页,笔记
        *//*
        //总数量
        int totalElements = noteManageService.findNoteList(user.getUserId(), cid, baseKey, page, 0).size();
        //有几页
        int totalPages = totalElements % size == 0 ? totalElements / size : totalElements / size + 1;
        List<AoaNoteList> noteList = noteManageService.findNoteList(user.getUserId(), cid, baseKey, (page - 1) * size, size);



        HashMap<String, Integer> map1 = new HashMap<>();
        map1.put("totalElements", totalElements);
        map1.put("totalPages", totalPages);




        model.addAttribute("page", map1);



        model.addAttribute("nlist", noteList);
        model.addAttribute("url", "notewrite");

        HashMap<String, Integer> map1 = new HashMap<>();
        map1.put("totalElements", totalElements);
        map1.put("totalPages", totalPages);




        return "note/notewrite";


        return"note/noteview";*/


        System.out.println(catalogId);

        AoaUser user = (AoaUser) session.getAttribute("user");

        //状态，类型
        model.addAttribute("statuslist",
                noteManageService.findStatus());
        model.addAttribute("typelist",
                noteManageService.findType());


        int totalElements = 0;
        int totalPages = 0;
        List<AoaNoteList> noteList = null;

        /*
         普通查询
         */
        if ("".equals(typeid)) {
            //笔记分类
            model.addAttribute("calist",
                    noteManageService.findCatalog(user.getUserId()));
            Integer cid = "".equals(catalogId) ? null : Integer.parseInt(catalogId);

            //总数量
            totalElements = noteManageService.findNoteList(user.getUserId(), cid, baseKey, page, 0).size();
            //有几页
            totalPages = totalElements % size == 0 ? totalElements / size : totalElements / size + 1;
            noteList = noteManageService.findNoteList(user.getUserId(), cid, baseKey, (page - 1) * size, size);
        } else {
             /*
            "我的笔记"
         */
            if ("5".equals(typeid)) {
                totalElements = noteDao.queryNoteByType(user.getUserId(), typeid, page, 0).size();
                totalPages = totalElements % size == 0 ? totalElements / size : totalElements / size + 1;
                noteList = noteDao.queryNoteByType(user.getUserId(), typeid, (page - 1) * size, size);
            }

        /*
         公司笔记
         */
            if ("6".equals(typeid)) {

                totalElements = noteDao.queryNoteByType(0, typeid, page, 0).size();
                totalPages = totalElements % size == 0 ? totalElements / size : totalElements / size + 1;
                noteList = noteDao.queryNoteByType(0, typeid, (page - 1) * size, size);
            }

        /*
        共享笔记
         */
            if ("7".equals(typeid)) {

                totalElements = noteDao.queryShareNote(user.getUserId(), page, 0).size();
                totalPages = totalElements % size == 0 ? totalElements / size : totalElements / size + 1;
                noteList = noteDao.queryShareNote(user.getUserId(), (page - 1) * size, size);

            }
        }


        HashMap<String, Integer> map1 = new HashMap<>();
        map1.put("totalElements", totalElements);
        map1.put("totalPages", totalPages);
        map1.put("number", page);
        map1.put("size", size);
        model.addAttribute("page", map1);
        model.addAttribute("nlist", noteList);
        model.addAttribute("url", "notewrite");
        model.addAttribute("typeid", typeid);
        return "note/noteview";


    }


    @RequestMapping("notewrite")
    public String notewrite
            (
                    Model model, HttpSession session,
                    @RequestParam(value = "baseKey", defaultValue = "") String baseKey,
                    @RequestParam(value = "page", defaultValue = "1") int page,
                    @RequestParam(value = "size", defaultValue = "8") int size,
                    @RequestParam(value = "catalogId", defaultValue = "") String catalogId,
                    @RequestParam(value = "typeid", defaultValue = "") String typeid
            ) {


        System.out.println(catalogId);

        AoaUser user = (AoaUser) session.getAttribute("user");

        //状态，类型
        model.addAttribute("statuslist",
                noteManageService.findStatus());
        model.addAttribute("typelist",
                noteManageService.findType());


        int totalElements = 0;
        int totalPages = 0;
        List<AoaNoteList> noteList = null;

        /*
         普通查询
         */
        if ("".equals(typeid)) {
            //笔记分类
            model.addAttribute("calist",
                    noteManageService.findCatalog(user.getUserId()));
            Integer cid = "".equals(catalogId) ? null : Integer.parseInt(catalogId);

            //总数量
            totalElements = noteManageService.findNoteList(user.getUserId(), cid, baseKey, page, 0).size();
            //有几页
            totalPages = totalElements % size == 0 ? totalElements / size : totalElements / size + 1;
            noteList = noteManageService.findNoteList(user.getUserId(), cid, baseKey, (page - 1) * size, size);
        } else {
             /*
            "我的笔记"
         */
            if ("5".equals(typeid)) {
                totalElements = noteDao.queryNoteByType(user.getUserId(), typeid, page, 0).size();
                totalPages = totalElements % size == 0 ? totalElements / size : totalElements / size + 1;
                noteList = noteDao.queryNoteByType(user.getUserId(), typeid, (page - 1) * size, size);
            }

        /*
         公司笔记
         */
            if ("6".equals(typeid)) {
                if ("6".equals(typeid)) {
                    totalElements = noteDao.queryNoteByType(0, typeid, page, 0).size();
                    totalPages = totalElements % size == 0 ? totalElements / size : totalElements / size + 1;
                    noteList = noteDao.queryNoteByType(0, typeid, (page - 1) * size, size);
                }


            }

        /*
        共享笔记
         */
            if ("7".equals(typeid)) {


                if ("7".equals(typeid)) {
                    totalElements = noteDao.queryShareNote(user.getUserId(), page, 0).size();
                    totalPages = totalElements % size == 0 ? totalElements / size : totalElements / size + 1;
                    noteList = noteDao.queryShareNote(user.getUserId(), (page - 1) * size, size);
                }
            }
        }


        HashMap<String, Integer> map1 = new HashMap<>();
        map1.put("totalElements", totalElements);
        map1.put("totalPages", totalPages);
        map1.put("number", page);
        map1.put("size", size);
        model.addAttribute("page", map1);
        model.addAttribute("nlist", noteList);
        model.addAttribute("url", "notewrite");
        model.addAttribute("typeid", typeid);
        return "note/notewrite";
    }


    /*
      @Description : 批量删除
      @Date   :  2021/12/1
      @Param  : [sum, page]
      @return : boolean
     */
    @RequestMapping("notesomedelete")
    public boolean notesomedelete(String sum, String page) {
        String[] noteId = sum.split(";");
        System.out.println(page);
        return noteManageService.notesomedelete(noteId);
    }


    /*
      @Description :删除一个
      @Date   :  2021/12/1
      @Param  : [nid, page]
      @return : java.lang.String
     */
    @RequestMapping("notedelete")
    public String notedelete(String catalogId, int page) {
        noteManageService.noteDeleteById(Integer.parseInt(catalogId));

        return "redirect:noteview?page=" + page;
    }


    /*
      @Description : 查看
      @Date   :  2021/12/1
      @Param  : [catalogId, model, page]
      @return : java.lang.String
     */
    @RequestMapping("noteinfo")
    public String noteinfo(String catalogId, Model model, String page) {
        AoaNoteList note = noteDao.selectByPrimaryKey(Long.parseLong(catalogId));

        model.addAttribute("note", note);


        model.addAttribute("createName", noteDao.queryNoteCreateUserNameByNoteId(catalogId));

        //查询笔记类型
        model.addAttribute("typeid", noteDao.queryNoteTypeIdByNoteId(catalogId));

        if (note.getAttachId() != null) {
            AoaAttachmentList attachmentList = noteDao.queryAttByNoteId(note.getAttachId());
            model.addAttribute("att", attachmentList);
        }

        return "note/noteinfo";
    }

    @RequestMapping("noteedit")
    public String noteedit(String catalogId, HttpSession session, Model model, String page, String id,

                           String dosome
    ) {
        /*
            修改
        */

        AoaUser user = (AoaUser) session.getAttribute("user");


        if ("u".equals(dosome)) {
            //父级
            model.addAttribute("calist", noteDao.queryCatalogByUserId(user.getUserId()));


            //状态，类型
            model.addAttribute("statuslist",
                    noteManageService.findStatus());
            model.addAttribute("typelist",
                    noteManageService.findType());
            AoaNoteList note = noteDao.selectByPrimaryKey(Long.parseLong(catalogId));
            model.addAttribute("note", note);
            model.addAttribute("cata", noteDao.findCatalogById(user.getUserId(), note.getCatalogId()));
            addressList(model, session);

        }
        if ("n".equals(dosome)) {


            if ("".equals(id) || id == null) {

                List<AoaCatalog> aoaCatalogs = noteService.selectByUserId(user.getUserId());
                model.addAttribute("calist", aoaCatalogs);

                List<AoaTypeList> noteList = noteService.selectByTypeModel("aoa_note_list");
                model.addAttribute("typelist", noteList);

                addressList(model, session);

                List<AoaStatusList> noteList1 = noteService.selectByStatusModel("aoa_note_list");
                model.addAttribute("statuslist", noteList1);
                return "note/noteedit2";

            } else {

                String regEx = "[^0-9]";
                Pattern pp = Pattern.compile(regEx);
                Matcher m = pp.matcher(id);

                model.addAttribute("cata", noteDao.findCatalogById(user.getUserId(), Integer.parseInt(m.replaceAll(""))));

                List<AoaCatalog> aoaCatalogs = noteService.selectByUserId(user.getUserId());
                model.addAttribute("calist", aoaCatalogs);

                List<AoaTypeList> noteList = noteService.selectByTypeModel("aoa_note_list");
                model.addAttribute("typelist", noteList);

                addressList(model, session);

                List<AoaStatusList> noteList1 = noteService.selectByStatusModel("aoa_note_list");
                model.addAttribute("statuslist", noteList1);
                return "note/noteedit2";

            }


        }

        model.addAttribute("thisPage", Integer.parseInt(page));
        System.out.println("page====" + page);

        return "note/noteedit";
    }


    @RequestMapping("notesave")
    public String notesave(HttpSession session, Model model,
                           String catalogname,
                           String type,
                           String status,
                           String title,
                           String content,
                           String noteId,
                           String dosome,
                           @RequestParam(value = "receiver", defaultValue = "") String receiver,
                           @RequestParam("file") MultipartFile file,
                           AoaNoteList aoaNoteList,
                           String thisPage
    ) {


        if ("u".equals(dosome)) {
            AoaUser user = (AoaUser) session.getAttribute("user");
            System.out.println(catalogname);
            Integer catalogId = noteDao.queryCatalogIdByName(user.getUserId(), catalogname);
            System.out.println(type);
            Integer typeId = noteDao.queryTypeIdByName(type);
            System.out.println(status);
            Integer statusId = noteDao.queryStatusIdByName(status);
            System.out.println(title);
            System.out.println(content);


            AoaNoteList note = new AoaNoteList();

            note.setNoteId(Long.parseLong(noteId));
            note.setCatalogId(catalogId);
            note.setTypeId(typeId);
            note.setStatusId(statusId);
            note.setContent(content);
            note.setTitle(title);
            note.setReceiver(receiver);


            /**
             * 副表添加
             */
            if (!"".equals(receiver)) {
                AoaReceiverNote aoaReceiverNote = new AoaReceiverNote();
                aoaReceiverNote.setNoteId(Integer.parseInt(aoaNoteList.getNoteId() + ""));
                String[] split = receiver.split(";");
                for (String s : split) {
                    AoaUser aoaUser = noteService.selectByUserName(s);
                    System.out.println(aoaUser);
                    aoaReceiverNote.setUserId(aoaUser.getUserId());
                    int insert = noteService.insert(aoaReceiverNote);
                    System.out.println("insert = " + insert);
                }
            }


            if (noteDao.notesave(note) > 0) {
                return "redirect:noteview?thisPage=" + thisPage;

            } else {
                return "";

            }

        }
        if ("n".equals(dosome)) {
            AoaUser user = (AoaUser) session.getAttribute("user");
            AoaCatalog aoaCatalog = noteService.selectByCatalogName(catalogname, user.getUserId());
            AoaTypeList aoaTypeList = noteService.selectByTypeName(type);
            AoaStatusList aoaStatusList = noteService.selectByStatusName(status);


            //获取系统当前时间
            /*Date date = new Date();
            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);*/


            aoaNoteList.setCatalogId(aoaCatalog.getCatalogId());
            aoaNoteList.setTypeId(aoaTypeList.getTypeId());
            aoaNoteList.setStatusId(aoaStatusList.getStatusId());
            aoaNoteList.setCreatemanId(user.getUserId());
            aoaNoteList.setCreateTime(DateUtils.getDateTimeString());
            aoaNoteList.setReceiver(receiver);

            //默认不收藏
            aoaNoteList.setIsCollected(0);


            /**
             * 附件
             */
            if (file.getSize() != 0) {
                //url
                String url = oosUtil.getImgUrl(oosUtil.uploadImg2Oss(file));
                String shuffix = oosUtil.getPicSuffix(file.getOriginalFilename());
                long size = file.getSize();
                String type2 = file.getContentType();
                AoaAttachmentList attachment = new AoaAttachmentList();
                attachment.setAttachmentName(file.getOriginalFilename());
                attachment.setAttachmentPath(url);
                attachment.setAttachmentSize(size + "");
                attachment.setAttachmentType(type2);
                attachment.setAttachmentShuffix(shuffix);
                attachment.setModel("note");
                attachment.setUploadTime(DateUtils.getDateTimeString());
                attachment.setUserId(user.getUserId() + "");
                newProcessService2.inertAttachment(attachment);
                System.out.println(attachment.getAttachmentId());
                aoaNoteList.setAttachId(attachment.getAttachmentId());

            }

            /**
             * 主表添加
             */
            noteService.insertSelective(aoaNoteList);

            /**
             * 副表添加
             */
            if (!"".equals(receiver)) {
                AoaReceiverNote aoaReceiverNote = new AoaReceiverNote();
                aoaReceiverNote.setNoteId(Integer.parseInt(aoaNoteList.getNoteId() + ""));
                String[] split = receiver.split(";");
                for (String s : split) {
                    AoaUser aoaUser = noteService.selectByUserName(s);
                    System.out.println(aoaUser);
                    aoaReceiverNote.setUserId(aoaUser.getUserId());
                    int insert = noteService.insert(aoaReceiverNote);
                    System.out.println("insert = " + insert);
                }
            }
        }
        return "redirect:/noteview?thispage=" + thisPage;

    }


    @RequestMapping("setCollected")
    public String setCollected(String id, String isCollected) {
        System.out.println("===================");
        String collected = "1".equalsIgnoreCase(isCollected) ? "0" : "1";


        noteDao.setNoteCollected(id, collected);

        return "redirect:noteview";
    }


    @RequestMapping("noteviewuuu")
    public String noteview(String name, HttpSession session) {
        AoaUser user = (AoaUser) session.getAttribute("user");

        noteDao.insertCatalog(user.getUserId(), name);

        return "redirect:/noteview";

    }

    @RequestMapping("catadelete")
    public String catadelete(String cid) {
        noteDao.deleteCatalogById(cid);

        return "redirect:/noteview";
    }


    /*
      @Description :    我的笔记
                        公司笔记
                        共享笔记

      @Date   :  2021/12/2
      @Param  : [typeid, session, model, baseKey, page, size]
      @return : java.lang.String
     */
    @RequestMapping("notetype")
    public String notetype(String typeid, HttpSession session, Model model,

                           @RequestParam(value = "baseKey", defaultValue = "") String baseKey,
                           @RequestParam(value = "page", defaultValue = "1") int page,
                           @RequestParam(value = "size", defaultValue = "8") int size
    ) {
        System.out.println("=======================");
        AoaUser user = (AoaUser) session.getAttribute("user");
        System.out.println(typeid);




        /*
         判断笔记类型并查询
        */
        List<AoaNoteList> noteLists = null;
        int totalElements = 0;
        int totalPages = 0;

        if ("5".equals(typeid)) {
            totalElements = noteDao.queryNoteByType(user.getUserId(), typeid, page, 0).size();
            totalPages = totalElements % size == 0 ? totalElements / size : totalElements / size + 1;
            noteLists = noteDao.queryNoteByType(user.getUserId(), typeid, (page - 1) * size, size);
        }

        if ("6".equals(typeid)) {
            totalElements = noteDao.queryNoteByType(0, typeid, page, 0).size();
            totalPages = totalElements % size == 0 ? totalElements / size : totalElements / size + 1;
            noteLists = noteDao.queryNoteByType(0, typeid, (page - 1) * size, size);
        }

        if ("7".equals(typeid)) {
            totalElements = noteDao.queryShareNote(user.getUserId(), page, 0).size();
            totalPages = totalElements % size == 0 ? totalElements / size : totalElements / size + 1;
            noteLists = noteDao.queryShareNote(user.getUserId(), (page - 1) * size, size);
        }

        //状态，类型
        model.addAttribute("statuslist",
                noteManageService.findStatus());
        model.addAttribute("typelist",
                noteManageService.findType());
        //笔记分类
        model.addAttribute("calist",
                noteManageService.findCatalog(user.getUserId()));
        model.addAttribute("nlist", noteLists);


        /*
          分页
        */
        HashMap<String, Integer> map1 = new HashMap<>();
        map1.put("totalElements", totalElements);
        map1.put("totalPages", totalPages);
        map1.put("number", page);
        map1.put("size", size);
        model.addAttribute("page", map1);
        model.addAttribute("nlist", noteLists);
        model.addAttribute("url", "notewrite");
        model.addAttribute("thisPage", page);
        model.addAttribute("typeid", typeid);

        return "note/notewrite";
    }


    /*
      @Description : 第一次通讯录
      @Date   :  2021/11/24
      @Param  : [model]
      @return : void
     */
    public void addressList(Model model, HttpSession session) {

        AoaUser aoaUser = (AoaUser) session.getAttribute("user");

        /*
              通讯录
        */
        int page = 1, size = 5;
        String baseKey = "";
        //计数
        int totalElements = noteDao.findUserInfoByName(baseKey, page, 0, aoaUser.getRoleId()).size();
        //页数
        int totalPages = totalElements % size == 0 ? totalElements / size : totalElements / size + 1;
        List<AoaUser> users = noteDao.findUserInfoByName(baseKey, page, size, aoaUser.getRoleId());
        Map<String, Object> mapPage = new HashMap<>();
        mapPage.put("totalElements", totalElements);
        mapPage.put("totalPages", totalPages);
        mapPage.put("number", page);
        mapPage.put("size", size);
        model.addAttribute("page", mapPage);
        model.addAttribute("url", "noterecivers");
        model.addAttribute("userInfo", users);
    }

    /*
   @Description : 通讯录
   @Date   :  2021/11/24
   @Param  : [model, baseKey, page, size]
   @return : java.lang.String
  */
    @RequestMapping("noterecivers")
    public String reciver(Model model, HttpSession session,
                          @RequestParam(value = "baseKey", defaultValue = "") String baseKey,
                          @RequestParam(value = "page", defaultValue = "1") int page,
                          @RequestParam(value = "size", defaultValue = "5") int size) {

        AoaUser aoaUser = (AoaUser) session.getAttribute("user");

        int totalElements = noteDao.findUserInfoByName(baseKey, page, 0, aoaUser.getRoleId()).size();
        int totalPages = totalElements % size == 0 ? totalElements / size : totalElements / size + 1;

        List<AoaUser> userInfos = noteDao.findUserInfoByName(baseKey, (page - 1) * size, size, aoaUser.getRoleId());
        model.addAttribute("userInfo", userInfos);

        Map<String, Object> mapPage = new HashMap<>();
        mapPage.put("totalElements", totalElements);
        mapPage.put("totalPages", totalPages);
        mapPage.put("number", page);
        mapPage.put("size", size);
        model.addAttribute("page", mapPage);
        model.addAttribute("url", "noterecivers");
        return "common/noterecivers";

    }


    @RequestMapping("deleteVerify")
    @ResponseBody
    public boolean deleteVerify(String noteId, HttpSession session) {
        System.out.println("deleteVerify");
        System.out.println(noteId);

        //根据noteID 查询用户 id
        Integer userId = noteDao.quertNoteUserIdByNoteId(noteId);

        AoaUser aoaUser = (AoaUser) session.getAttribute("user");

        if (aoaUser.getUserId() != userId) {
            return false;
        }

        return true;
    }


    @RequestMapping("batchCollect")
    @ResponseBody
    public int batchCollect(String noteId) {


        String[] noteIds = noteId.split(";");

        for (int i = 0; i < noteIds.length; i++) {
            noteDao.updateCollectBynoteId(noteIds[i]);
        }


        return 1;


    }


}
